import * as VueRouter from 'vue-router'
import { useStore } from 'vuex'
import NProgress from 'nprogress'
import Request from '@/request'


const modules = import.meta.glob('@/views/**/*.vue')

const Layout = () => import('@/layout/index.vue')

const routes = [
    {
        path: '/',
        name: 'Home',
        component: Layout
    },
    {
        path: '/login',
        name: 'Login',
        meta: {
            title: '登录'
        },
        component: () => import('@/views/login/index.vue')
    }
]

const after = [
    {
        path: '/:pathMatch(.*)*',
        name: 'NotFound',
        alias: '/error/404',
        meta: {
            title: '页面不存在！'
        },
        component: () => import('@/views/error/404.vue')
    }
]

const router = VueRouter.createRouter({
    history: VueRouter.createWebHashHistory(),
    routes
})


NProgress.configure({
    showSpinner: false
})


router.beforeEach(async (to, from, next) => {
    NProgress.start()
    const store = useStore()

    if (Object.keys(to.meta).length) {
        document.title = to.meta.title + ' - 后台管理'
    }

    const whiteList = ['Login']

    const token = localStorage.getItem('token')
    if (token) {
        const menu = store.state.system.menu
        if (menu.length) {
            to.name === 'Login' ? next('/') : next()
        } else {
            const res = await Request.get('/system/index')
            if (res.code) {
                toLogin(next, to)
            } else {
                store.dispatch('system/setMenu', res.datas.menu)
                store.dispatch('system/setUser', res.datas.user)
                getMenu(res.datas.menu)

                after.forEach(item => {
                    router.addRoute(item)
                })
                
                to.name === 'Login' ? next('/') : next(to.fullPath)
            }
        }
    } else {
        if (whiteList.indexOf(to.name) != -1) {
            next()
        } else {
            toLogin(next, to)
        }
    }
})

router.afterEach(() => {
    NProgress.done()
})

const toLogin = (next, to) => {
    next({
        name: 'Login',
        query: {
            redirect: to.fullPath
        }
    })
}


const getMenu = (datas, name) => {
    datas.forEach(item => {
        item.component = item.component ? item.component == 'Layout' ? Layout : modules[`${item.component}`] : null
        name == undefined ? router.addRoute(item) : router.addRoute(name, item)
        if (item.children && item.children.length) {
            getMenu(item.children, item.name)
        }
    })
}

export default router